package servlets;

import model.History;
import model.User;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import services.HistoryServices;
import utils.MyJSONUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 获得，删除，同步历史记录的servlet
 */
@WebServlet(name = "HistoryServlet", urlPatterns = "/history")
public class HistoryServlet extends HttpServlet {
    /**
     * 获得指定名字的cookies
     *
     * @param arr
     * @param name
     * @return
     */
    private Cookie getCookiesByName(Cookie[] arr, String name) {
        for (Cookie c : arr) {
            if (c.getName().equals(name)) {
                return c;
            }
        }
        return null;
    }

    //删除历史记录
    private void delete(HttpServletRequest request, HttpServletResponse response) {
        String comicId = request.getParameter("comicid");
        try {
            PrintWriter pw = response.getWriter();
            User user = (User) request.getSession().getAttribute("user");
            boolean result = false;
            if (user != null) {
                //用户已经登录
                HistoryServices historyServices = new HistoryServices();
                result = historyServices.deleteHistory(user.getUser_name(), comicId);
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("success", result);
            pw.write(jsonObject.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //返回list
    private void get(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter pw = response.getWriter();

        HistoryServices historyServices = new HistoryServices();
        List<History> list = null;

        User user = (User) request.getSession().getAttribute("user");
        if (user != null) {
            //用户已经登录
            list = historyServices.getHistoryByServer(user.getUser_name());//
        } else {
            //没有登录的情况下根据cookies
            Cookie historyCook = getCookiesByName(request.getCookies(), "history");
            if (historyCook != null) {
                String cookValue = historyCook.getValue();
                list = historyServices.getHistoryByHost(cookValue);//
            }
        }

        pw.write(JSONArray.fromObject(list, MyJSONUtils.jsonConfig).toString());
    }

    private void sync(HttpServletRequest request, HttpServletResponse response) {
        HistoryServices historyServices = new HistoryServices();
        try {
            PrintWriter pw = response.getWriter();

            User user = (User) request.getSession().getAttribute("user");
            if (user != null) {
                //获取历史记录
                Cookie historyCook = getCookiesByName(request.getCookies(), "history");
                if (historyCook != null) {
                    String historyJson = historyCook.getValue();//从cookies中获得history json数据
                    historyServices.addHostHistories(historyJson, user.getUser_name());
                }
            }

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("result", true);
            jsonObject.put("msg", "已经提交!请刷新页面查看最新历史记录");
            pw.write(jsonObject.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String type = request.getParameter("type");
        switch (type) {
            case "get":
                get(request, response);
                break;
            case "delete":
                delete(request, response);
                break;
            case "sync":
                sync(request, response);
                break;
        }

    }
}
